package model

const (
	ExchangeEnabled = 1
	ExchangeDisabled = 0
	exchangeRecommend = 1
)

type exchangeModel struct {
	Table 		string
}

var ExchangeModel = &exchangeModel{
	Table: 		"exchange",
}

// 插入一条
func (m *exchangeModel) Insert(data *Exchange) (bool, error) {
	row, err := MainDB.Insert(data)
	if err != nil {
		return false, err
	}
	return row > 0, err
}

// 批量插入
func (m *exchangeModel) InsertMulti(datas []*Exchange) error {
	_, err := MainDB.Insert(datas)
	return err
}

// 获取所有交易所
func (m *exchangeModel) AllEnabled() ([]*Exchange, error) {
	var exchanges []*Exchange
	err := MainDB.Table(m.Table).Where("enable=?", ExchangeEnabled).Find(&exchanges)
	if err != nil {
		return nil, err
	}
	return exchanges, nil
}

// 获取推荐的交易所
func (m *exchangeModel) GetRecommend(limit int) ([]*Exchange, error) {
	var exchanges []*Exchange
	err := MainDB.Table(m.Table).
		Where("recommend = ?", exchangeRecommend).
		Desc("recommend_sort").
		Limit(limit).
		Find(&exchanges)
	if err != nil {
		return nil, err
	}
	return exchanges, nil
}

// 通过 slug 获取交易所
func (m *exchangeModel) GetItemBySlug(slug string) (bool, *Exchange, error) {
	var exchange Exchange
	has, err := MainDB.Where("slug=?", slug).Get(&exchange)
	if err != nil {
		return false, nil, err
	}
	if has {
		return true, &exchange, nil
	}
	return false, nil, nil
}